<?php

namespace App\Http\Controllers;

use App\Jobs\DelFileAfterDownload;
use App\Models\ActionLog;
use App\Models\Company;
use App\Models\CompanyUser;
use App\Models\Role;
use App\Models\User;
use App\Services\AttachmentService;
use App\Services\CutPdfService;
use Illuminate\Http\Request;

class CutPdfController extends Controller
{
    public $cutPdfService;

    public function __construct(CutPdfService $cutPdfService)
    {
        parent::__construct();
        $this->cutPdfService = $cutPdfService;
    }

    /**
     * 展示页面
     */
    public function cutPdf(Request $request)
    {
        $partCompanyId     = htmlspecialchars($request->input('part_company_id'));
        $projectClassifyId = htmlspecialchars($request->input('project_classify_id'));
        $archivesNo        = htmlspecialchars($request->input('archives_no'));
        $userId            = htmlspecialchars($request->input('user_id'));
        $companyId         = htmlspecialchars($request->input('company_id'));
        $params = [
            'part_company_id'     => $partCompanyId,
            'project_classify_id' => $projectClassifyId,
            'archives_no'         => $archivesNo,
            'user_id'             => $userId,
            'company_id'          => $companyId,
        ];

        return view('cut_pdf', ['params' => $params]);
    }

    /**
     * 上传 PDF
     */
    public function uploadPDF(Request $request)
    {
        $file = $request->file('file');
        $res  = (new AttachmentService())->upload($file, 'local');
        $data = 'storage/' . $res['file'];

        return $this->success($data);
    }

    /**
     * 检查档案号
     */
    public function check(Request $request)
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = htmlspecialchars($request->input('project_classify_id'));
        $archivesNo        = $request->input('archives_no');
        $pdfPath           = $request->input('pdf_path');
        if (empty($pdfPath)) {
            return $this->error('请上传文件!');
        }
        $archivesNo = format_archives_no($archivesNo); //格式化档案号
        $result     = $this->cutPdfService->checkData($partCompanyId, $projectClassifyId, $archivesNo, $pdfPath);
        if (!empty($result['msg'])) {
            return $this->error($result['msg']);
        }

        return $this->success($result['data']);
    }

    /**
     * 分割 PDF为若干部分
     */
    public function cutPdfAction(Request $request)
    {
        $pdfPath     = $request->input('pdf_path');
        $archivesNo  = $request->input('archives_no');
        $userId      = $request->input('user_id');
        $companyId   = $request->input('company_id');

        if (str_contains($archivesNo, '/')) {
            $archivesNo = str_replace('/', '-', $archivesNo); //把反斜杠替换为斜杠
        }

        $result  = $this->cutPdfService->cutPdf($archivesNo, $pdfPath); //执行PDF分割

        /**
         * 下面写入日志记录，这里需要单独写，因为这是web页面，没办法使用company_id()和user_id()，二者在系统中是通过dingo/api获取的
         */
        $user    = User::query()->find($userId);
        $company = Company::query()->find($companyId);
        $roleId  = CompanyUser::query()->where('company_id', $companyId)->where('user_id', $userId)->value('role_id');
        $role    = Role::query()->find($roleId);
        $data    = [
            'user_id'      => $userId,
            'company_id'   => $companyId,
            'user_name'    => $user->nickname,
            'company_name' => $company->title,
            'role_name'    => $role->title,
            'event'        => '分割PDF',
            'detail'       => "档案号:{$archivesNo},共{$result['pdf_count']}页,生成{$result['cut_pdf_num']}个PDF",
            'created_at'   => now(),
        ];
        $loginIp  = request()->ip();
        $address  = (new \Ip2Region())->simple($loginIp);
        if ($address && $address != '内网IP') {
            $address  = substr($address, 0, strpos($address, '【')); //去掉运营商【移动】
            $address  = substr($address, strpos($address, '中国') + 6); //去掉国家
        }
        $data['action_ip'] = $loginIp;
        $data['address']   = $address ?? '未知地址';
        ActionLog::query()->insert($data);
        /** 日志写入完毕 */

        return $this->success($result['download_url']);
    }

    /**
     * 执行任务，把生成的文件下载后 10分钟后删除 storage/files/20230404/949246b286dc563c1785d0e1484f1c9a.pdf
     */
    public function delFileAfterDownload($archivesNo, $pdfPath)
    {
        $filePaths = [
            'origin_pdf' => $pdfPath,
            'file'       => '/public/cutPdf/' . $archivesNo . '.zip',
            'dir'        => '/public/cutPdf/' . $archivesNo,
        ];
        DelFileAfterDownload::dispatch($filePaths)->delay(now()->addMinutes(10)); //分发任务
    }


}
